#!/usr/bin/env python
#coding=utf-8
import random
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest


def send_sms(phone,code):
    """
    阿里云短信验证接口
    """
    client = AcsClient('LTAIwI4UxO3cKQd5', 'NLa2cQMT0fM7eDrGnY5Ec5kf1QtegK', 'cnhangzhou')

    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https') # https | http
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')

    request.add_query_param('RegionId', 'cn-hangzhou')
    request.add_query_param('PhoneNumbers',phone)
    request.add_query_param('SignName', '北网人工')
    request.add_query_param('TemplateCode', 'SMS_163055570')
    request.add_query_param('TemplateParam', {'code':code})

    response = client.do_action(request)
    print(str(response, encoding = 'utf-8'))
    return str(response, encoding = 'utf-8')


def get_code(n=6, alpha=True):
    """
    获取随机的6位验证码
    """
    a = ""
    for i in range(n):
        ch = chr(random.randrange(ord('0'), ord('9') + 1))

        if alpha:  # 需要字母验证码,不用传参,如果不需要字母的,关键字alpha=False            
            upper_alpha = chr(random.randint(65, 90))
            lower_alpha = chr(random.randint(97, 122))
            ch = random.choice([ch, upper_alpha, lower_alpha])
        a = a + str(ch)
    return a


if __name__ == '__main__':




    send_sms('15835740186', get_code(6,False))
    #print(get_code(6,False)) # 打印6位数字验证码    
    # print(get_code(6,True))# 打印6位数字字母混合验证码    
    # print(get_code(4,False))# 打印4位数字验证码    
    # print(get_code(4,True)) # 打印4位数字字母混合验证码
